import pymysql
class DBUtil(object):
    conn=None
    @classmethod
    def __connect_db(cls):
        cls.conn = pymysql.connect(host="211.103.136.244", port=7061, user="student",
        password="iHRM_student_2021", database="ihrm", charset="utf8")
        return cls.conn

    @classmethod
    def __close_db(cls):
        cls.conn.close()
    # 1.对查询数据的封装
    @classmethod
    def get_one(cls, sql):
        cursor=None
        result=None
        try:
            cls.conn=cls.__connect_db()
            # 获取游标
            cursor = cls.conn.cursor()
            # 执行sql语句
            cursor.execute(sql)
            result = cursor.fetchone()
        except Exception as err:
            print("错误信息：",err)
        finally:
            cursor.close()
            cls.__close_db()
            return result

    # 2.对数据增删改的封装
    @classmethod
    def uid_db(cls, sql):
        cursor = None
        result = None
        try:
            cls.conn = cls.__connect_db()
            # 获取游标
            cursor = cls.conn.cursor()
            # 执行sql语句
            cursor.execute(sql)
            cls.conn.commit()
            result = cls.conn.affected_rows()
            print('影响的行数：',result)
        except Exception as err:
            print("错误信息：", err)
            cls.conn.rollback()
        finally:
            cursor.close()
            cls.__close_db()

if __name__ == '__main__':
    # result_query = DBUtil.get_one("SELECT  * from t_book ;")
    # print("result_query=", result_query)
    result_query = DBUtil.uid_db("update t_book set `read` = `read`+1 where id=1;")
